package com.qf.controller;


import com.qf.annotation.ProccessInfo;
import com.qf.commons.TableData;
import com.qf.entity.EndUser;
import com.qf.exception.BizException;
import com.qf.exception.ControllerException;
import com.qf.service.EndUserService;
import com.qf.utils.DateUtils;
import com.qf.utils.StringUtils;
import org.jctools.maps.NonBlockingHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

@CrossOrigin("*")
@RestController
@RequestMapping("/endUser")
public class EndUserController {
    @Value("${fileDownloadLocation}")
    private  String fileDownloadLocation;

    @Value("${excelPath}")
    private  String excelPath;


    private EndUserService endUserService;

    public EndUserController(EndUserService endUserService) {
        this.endUserService = endUserService;
    }


//    动态查询
    @ProccessInfo(value = "后端用户修改1", requireParamInfo = true)
    @GetMapping
    public Object getAll(@RequestParam(defaultValue = "0") Integer offset,
                         @RequestParam(defaultValue = "10")  Integer limit){

       // NonBlockingHashMap<String,Object> nonBlockingHashMap = new NonBlockingHashMap<>();


        TableData<EndUser> tableData = null;
        try {
            tableData = endUserService.QueryAll(offset, limit);

        }catch (BizException e){
            throw e;
        }
        catch (Exception e) {
           throw new ControllerException("控制层查询错误");
        }


        return tableData;
    }

//    动态修改
    @ProccessInfo(value = "后端用户修改", requireParamInfo = true)
    @PutMapping
    public Object change(EndUser user){
        Integer integer=0;
        try {
            integer = endUserService.changeUser(user);
        }catch (BizException e){
            throw e;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("控制层修改用户错误");
        }

        return  dataMap(integer,integer<1?"修改出错":"修改成功");
    }

    //添加用户

    @PostMapping
    @ProccessInfo(value = "添加用户", requireParamInfo = true)
    public Object addUser(EndUser user){
        Integer integer = 0;
        try {
            integer= endUserService.insertUser(user);
        }catch (BizException e){
            throw e;
        }catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("控制层添加用户错误");
        }
        return dataMap(integer,integer<1?"添加用户出错":"添加成功");
    }


    @GetMapping("/downloadexcel")
    @ProccessInfo(value = "上传excel文件", requireParamInfo = true)
    public void downloadExcel(HttpServletResponse response){

        try {
            //根据时间生成文件名  20200630164834.xls
            String fileName = DateUtils.transferDateToStr(new Date(), DateUtils.DATE_KEY_STR) + ".xls";
            String fullPath = endUserService.generateExcel(fileName);

            fileName = URLEncoder.encode(fileName, "utf-8");

            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            File file = new File(fullPath);
            if (file.exists()){
                FileCopyUtils.copy(new FileInputStream(fullPath), response.getOutputStream());
            }else {
                System.out.println("文件不存在");
            }

        } catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
    }

    @PostMapping("/uploadExcel")
    @ProccessInfo(value = "excel导入信息", requireParamInfo = true)
    public Object uploadExcel(MultipartFile excel){
        // 获取文件的原始名字
        String originFileName = excel.getOriginalFilename();

        // 获取文件的后缀： .png .jpg XXXX
        String fileSuffix = originFileName.substring(originFileName.lastIndexOf("."));

        // 新的文件名
        String newFileName = System.nanoTime() + StringUtils.generateRandomString(10) + fileSuffix;
        String filePath = fileDownloadLocation + newFileName;
        Integer integer=0;
        try {
            excel.transferTo(new File(filePath));  // D:/nginx-server/images/8877776656afeji786766.png
           integer= endUserService.fileToSql(filePath);

        } catch (IOException ioException) {
            throw new ControllerException(ioException.getMessage());
        }
        if (integer>0){
            return dataMap(1,"导入成功");
        }else {
            return dataMap(0,"导入失败");
        }

    }

    @GetMapping("/excelmodel")
    @ProccessInfo(value = "下载excel文件", requireParamInfo = true)
    public void getExcelModel(HttpServletResponse response){
        try {
             String   fileName = URLEncoder.encode("endUserExcelModel.xls", "utf-8");

            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            FileCopyUtils.copy(new FileInputStream(excelPath+"endUserExcelModel.xls"),
                    response.getOutputStream());
        } catch (IOException e) {
            throw new ControllerException("控制层下载excel文件错误");
        }
    }

    @GetMapping("/userInfo")
    public Object viewNameImg(HttpSession session){
        return session.getAttribute("endUser");
    }


    public NonBlockingHashMap<String, Object> dataMap(Integer num,String msg) {
        NonBlockingHashMap<String, Object> map =
                new NonBlockingHashMap<>();

        map.put("code",num);
        map.put("msg",msg);

        return map;
    }

}
